import {
	Config
} from './config.js'
import {
	Token
} from './token.js'

const tips = {
	1: '抱歉，出现了一个错误',
	1005: 'token无效或不存在',
	3000: '请求数据不存在'
}

class Http {
	request(params, noRefetch) {
		let that = this
		if (!params.method) {
			params.method = 'GET'
		}
		uni.request({
			url: Config.api_base_url + params.url,
			method: params.method,
			data: params.data,
			header: {
				'content-type': 'application/json',
				'authorization': `Bearer ${uni.getStorageSync('token')}`
			},
			success(res) {
				let code = res.statusCode.toString()
				if (code.startsWith('2')) {
					params.success && params.success(res.data)
				} else {
					if (code == '401') {
						if (!noRefetch) {
							that._refetch(params);
						}
					}

					if (code == '404' || code == '400') {
						uni.showToast({
							title: res.data.message,
							icon: 'none',
							duration: 3000
						})
						return
					}

					if (noRefetch) {
						params.eCallback && params.eCallback(res);
					}
					let errorCode = res.data.error_code
					this._showError(errorCode)
					return
				}
			},
			fail: (err) => {
				this._showError(1)
			}
		})
	}

	_refetch(params) {
		var tokenModel = new Token()
		tokenModel.getTokenFromServer((token) => {
			this.request(params, true);
		});
	}

	_showError(errorCode) {
		if (!errorCode) {
			errorCode = 1
		}
		const tip = tips[errorCode]
		uni.showToast({
			title: tip ? tip : tips[1],
			icon: 'none',
			duration: 2000
		})
	}

	uploadImage(imgData, callback) {
		uni.uploadFile({
			url: Config.api_base_url + '/upload/qiniu',
			filePath: imgData,
			name: 'file',
			header: {
				'content-type': 'multipart/form-data',
				'token': uni.getStorageSync('token')
			},
			success: function(res) {
				callback && callback(res.data)
			}
		})
	}
}

export {
	Http
}
